package io.github.wanggit.antcms.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.wanggit.antcms.server.domain.AntArticle;
import io.github.wanggit.antcms.server.domain.AntArticleCatalog;
import io.github.wanggit.antcms.server.mapper.AntArticleCatalogMapper;
import io.github.wanggit.antcms.server.service.ArticleCatalogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ArticleCatalogServiceImpl
        extends ServiceImpl<AntArticleCatalogMapper, AntArticleCatalog>
        implements ArticleCatalogService {
    @Override
    public void saveOrUpdateRelations(List<Long> catalogIds, AntArticle antArticle) {
        if (null == catalogIds || null == antArticle) {
            return;
        }
        QueryWrapper<AntArticleCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", antArticle.getId());
        remove(queryWrapper);
        List<AntArticleCatalog> articleCatalogs = new ArrayList<>();
        catalogIds.forEach(
                it -> {
                    AntArticleCatalog articleCatalog = new AntArticleCatalog();
                    articleCatalog.setArticleId(antArticle.getId());
                    articleCatalog.setCatalogId(it);
                    articleCatalogs.add(articleCatalog);
                });
        saveBatch(articleCatalogs);
    }

    @Override
    public List<AntArticleCatalog> findRelationsByArticle(AntArticle article) {
        QueryWrapper<AntArticleCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", article.getId());
        return list(queryWrapper);
    }

    @Override
    public void deleteRelationsByArticle(AntArticle article) {
        QueryWrapper<AntArticleCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", article.getId());
        remove(queryWrapper);
    }
}
